<template>
  <el-dialog
    title="字段关系管理"
    v-model="dialogVisible"
    width="80%"
    destroy-on-close
       :modal="true"
    :append-to-body="true"
    :lock-scroll="true"
    class="relation-dialog"
  >
    <div class="relation-container" v-loading="loading">
      <div class="toolbar">
        <el-button-group>
          <el-button type="primary" @click="refreshRelationships">
            <el-icon><Refresh /></el-icon> 刷新关系
          </el-button>
          <el-button type="success" @click="detectRelationships">
            <el-icon><Connection /></el-icon> 自动检测关系
          </el-button>
        </el-button-group>

        <el-select v-model="viewMode" placeholder="选择视图模式">
          <el-option label="图表视图" value="graph" />
          <el-option label="表格视图" value="table" />
        </el-select>
      </div>

      <!-- 图形关系视图 -->
      <div v-if="viewMode === 'graph'" class="graph-view">
        <div class="graph-container" ref="graphContainer"></div>

        <el-card v-if="selectedRelationship" class="relation-detail-card">
          <template #header>
            <div class="card-header">
              <span>关系详情</span>
              <el-button-group>
                <el-button type="primary" size="small" @click="saveRelationship">
                  <el-icon><Check /></el-icon> 保存
                </el-button>
                <el-button type="danger" size="small" @click="deleteRelationship">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </el-button-group>
            </div>
          </template>

          <el-form label-width="100px" size="small">
            <el-form-item label="源字段">
              <el-select v-model="selectedRelationship.source_field_id" filterable>
                <el-option
                  v-for="field in fieldOptions"
                  :key="field.value"
                  :label="field.label"
                  :value="field.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="目标字段">
              <el-select v-model="selectedRelationship.target_field_id" filterable>
                <el-option
                  v-for="field in fieldOptions"
                  :key="field.value"
                  :label="field.label"
                  :value="field.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="关系类型">
              <el-select v-model="selectedRelationship.relationship_type">
                <el-option label="一对一" value="one_to_one" />
                <el-option label="一对多" value="one_to_many" />
                <el-option label="多对一" value="many_to_one" />
                <el-option label="多对多" value="many_to_many" />
                <el-option label="父子" value="parent_child" />
                <el-option label="参照" value="reference" />
              </el-select>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="selectedRelationship.description" type="textarea" :rows="2" />
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 表格关系视图 -->
      <div v-else class="table-view">
        <div class="table-actions">
          <el-button type="primary" @click="showAddRelationDialog">
            <el-icon><Plus /></el-icon> 添加关系
          </el-button>
        </div>

        <el-table :data="relationships" border style="width: 100%" v-loading="loading">
          <el-table-column label="源字段" min-width="150">
            <template #default="scope">
              {{ getFieldName(scope.row.source_field_id) }}
            </template>
          </el-table-column>
          <el-table-column label="关系类型" width="120">
            <template #default="scope">
              <el-tag :type="getRelationshipTagType(scope.row.relationship_type)">
                {{ getRelationshipTypeLabel(scope.row.relationship_type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="目标字段" min-width="150">
            <template #default="scope">
              {{ getFieldName(scope.row.target_field_id) }}
            </template>
          </el-table-column>
          <el-table-column label="描述" min-width="200" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.description || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button-group>
                <el-button type="primary" link @click="editRelationship(scope.row)">
                  <el-icon><Edit /></el-icon> 编辑
                </el-button>
                <el-button type="danger" link @click="confirmDeleteRelationship(scope.row)">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加/编辑关系对话框 -->
    <el-dialog
      :title="isEditingRelation ? '编辑关系' : '添加关系'"
      v-model="relationFormVisible"
      width="500px"
      append-to-body
      destroy-on-close
    >
      <el-form
        :model="relationForm"
        label-width="100px"
        :rules="relationFormRules"
        ref="relationFormRef"
      >
        <el-form-item label="源字段" prop="source_field_id">
          <el-select v-model="relationForm.source_field_id" filterable placeholder="选择源字段">
            <el-option
              v-for="field in fieldOptions"
              :key="field.value"
              :label="field.label"
              :value="field.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关系类型" prop="relationship_type">
          <el-select v-model="relationForm.relationship_type" placeholder="选择关系类型">
            <el-option label="一对一" value="one_to_one" />
            <el-option label="一对多" value="one_to_many" />
            <el-option label="多对一" value="many_to_one" />
            <el-option label="多对多" value="many_to_many" />
            <el-option label="父子" value="parent_child" />
            <el-option label="参照" value="reference" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标字段" prop="target_field_id">
          <el-select v-model="relationForm.target_field_id" filterable placeholder="选择目标字段">
            <el-option
              v-for="field in fieldOptions"
              :key="field.value"
              :label="field.label"
              :value="field.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="relationForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入关系描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="relationFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRelationForm" :loading="submitting"
            >确认</el-button
          >
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted, defineProps, defineEmits, watch, nextTick } from 'vue'
import { Refresh, Connection, Check, Delete, Plus, Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDatasetFields, getDatasetRelationships } from '@/api/dataset'
import * as echarts from 'echarts'

const props = defineProps({
  modelValue: Boolean,
  datasetId: [String, Number],
})

const emit = defineEmits(['update:modelValue'])

// 对话框可见性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
})

// 状态
const loading = ref(false)
const submitting = ref(false)
const viewMode = ref('graph')
const relationships = ref([])
const fields = ref([])
const graphChart = ref(null)
const graphContainer = ref(null)
const selectedRelationship = ref(null)
const relationFormVisible = ref(false)
const isEditingRelation = ref(false)
const relationFormRef = ref(null)

// 构建字段选项
const fieldOptions = computed(() => {
  return fields.value.map((field) => ({
    label: field.display_name || field.name,
    value: field.id,
  }))
})

// 关系表单数据
const relationForm = reactive({
  id: null,
  source_field_id: '',
  target_field_id: '',
  relationship_type: 'reference',
  description: '',
})

// 表单校验规则
const relationFormRules = {
  source_field_id: [{ required: true, message: '请选择源字段', trigger: 'change' }],
  target_field_id: [{ required: true, message: '请选择目标字段', trigger: 'change' }],
  relationship_type: [{ required: true, message: '请选择关系类型', trigger: 'change' }],
}

// 获取关系类型标签
const getRelationshipTypeLabel = (type) => {
  const typeMap = {
    one_to_one: '一对一',
    one_to_many: '一对多',
    many_to_one: '多对一',
    many_to_many: '多对多',
    parent_child: '父子',
    reference: '参照',
  }
  return typeMap[type] || type
}

// 获取关系类型标签样式
const getRelationshipTagType = (type) => {
  const typeMap = {
    one_to_one: 'primary',
    one_to_many: 'success',
    many_to_one: 'warning',
    many_to_many: 'danger',
    parent_child: 'info',
    reference: '',
  }
  return typeMap[type] || ''
}

// 根据字段ID获取字段名称
const getFieldName = (fieldId) => {
  const field = fields.value.find((f) => f.id === fieldId)
  return field ? field.display_name || field.name : '未知字段'
}

// 获取关系图的配置
const getGraphOption = () => {
  // 节点数据（字段）
  const nodes = fields.value.map((field) => ({
    id: field.id,
    name: field.display_name || field.name,
    symbolSize: 40,
    category: field.category || 'other',
  }))

  // 边数据（关系）
  const edges = relationships.value.map((rel) => ({
    source: rel.source_field_id,
    target: rel.target_field_id,
    value: getRelationshipTypeLabel(rel.relationship_type),
    label: {
      show: true,
      formatter: getRelationshipTypeLabel(rel.relationship_type),
    },
    lineStyle: {
      color: getRelationshipTypeColor(rel.relationship_type),
      width: 2,
      curveness: 0.2,
    },
  }))

  // 类别数据（字段类别）
  const categories = [
    { name: 'dimension' },
    { name: 'measure' },
    { name: 'time' },
    { name: 'id' },
    { name: 'other' },
  ]

  return {
    tooltip: {
      formatter: (params) => {
        if (params.dataType === 'edge') {
          const rel = relationships.value.find(
            (r) =>
              r.source_field_id === params.data.source && r.target_field_id === params.data.target,
          )
          return rel ? `${params.data.value}<br/>${rel.description || ''}` : params.data.value
        } else {
          return params.data.name
        }
      },
    },
    legend: {
      data: categories.map((cat) => cat.name),
    },
    series: [
      {
        type: 'graph',
        layout: 'force',
        data: nodes,
        links: edges,
        categories: categories,
        roam: true,
        label: {
          show: true,
          position: 'right',
        },
        force: {
          repulsion: 200,
          edgeLength: 120,
        },
        emphasis: {
          focus: 'adjacency',
          lineStyle: {
            width: 4,
          },
        },
      },
    ],
  }
}

// 获取关系类型对应的颜色
const getRelationshipTypeColor = (type) => {
  const colorMap = {
    one_to_one: '#409EFF',
    one_to_many: '#67C23A',
    many_to_one: '#E6A23C',
    many_to_many: '#F56C6C',
    parent_child: '#909399',
    reference: '#606266',
  }
  return colorMap[type] || '#606266'
}

// 初始化图表
const initGraph = () => {
  if (!graphContainer.value) return

  if (graphChart.value) {
    graphChart.value.dispose()
  }

  graphChart.value = echarts.init(graphContainer.value)
  graphChart.value.setOption(getGraphOption())

  // 添加图例点击事件拦截以解决Cannot read properties of undefined (reading 'type')错误
  graphChart.value.on('legendselectchanged', function (params) {
    try {
      // 图例点击事件的安全处理
      if (!params || !params.selected) return
      console.log('Legend selected change:', params)
    } catch (error) {
      console.error('图例点击事件处理错误:', error)
    }
  })

  // 点击事件
  graphChart.value.on('click', (params) => {
    if (params.dataType === 'edge') {
      // 点击了一条边（关系）
      const rel = relationships.value.find(
        (r) => r.source_field_id === params.data.source && r.target_field_id === params.data.target,
      )
      if (rel) {
        selectedRelationship.value = { ...rel }
      }
    } else {
      // 点击了节点，可以清除选择
      selectedRelationship.value = null
    }
  })

  // 自适应大小
  window.addEventListener('resize', () => {
    graphChart.value && graphChart.value.resize()
  })
}

// 获取字段列表
const fetchFields = async () => {
  if (!props.datasetId) return

  try {
    const res = await getDatasetFields(props.datasetId)
    if (Array.isArray(res)) {
      fields.value = res
    } else {
      fields.value = []
    }
  } catch (error) {
    console.error('获取字段列表失败:', error)
    ElMessage.error('获取字段列表失败: ' + (error.message || '未知错误'))
  }
}

// 获取关系列表
const fetchRelationships = async () => {
  if (!props.datasetId) return

  loading.value = true
  try {
    const res = await getDatasetRelationships(props.datasetId)
    if (Array.isArray(res)) {
      relationships.value = res
    } else {
      relationships.value = []
    }
  } catch (error) {
    console.error('获取关系列表失败:', error)
    ElMessage.error('获取关系列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 刷新关系
const refreshRelationships = async () => {
  await fetchRelationships()
  if (viewMode.value === 'graph') {
    nextTick(() => {
      initGraph()
    })
  }
}

// 自动检测关系
const detectRelationships = async () => {
  if (!props.datasetId) return

  loading.value = true
  try {
    ElMessage.success('关系检测功能已启动，检测结果将很快显示')
    // 这里实际应该调用后端的关系检测API，目前我们简单刷新一下来模拟
    setTimeout(() => {
      refreshRelationships()
    }, 1000)
  } catch (error) {
    console.error('检测关系失败:', error)
    ElMessage.error('检测关系失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 保存关系更改
const saveRelationship = async () => {
  if (!selectedRelationship.value) return

  try {
    // 这里应调用保存关系的API
    ElMessage.success('关系已更新')
    // 更新本地数据
    const index = relationships.value.findIndex((r) => r.id === selectedRelationship.value.id)
    if (index !== -1) {
      relationships.value[index] = { ...selectedRelationship.value }
    }
    // 更新图表
    nextTick(() => {
      initGraph()
    })
  } catch (error) {
    console.error('保存关系失败:', error)
    ElMessage.error('保存关系失败: ' + (error.message || '未知错误'))
  }
}

// 删除关系
const deleteRelationship = async () => {
  if (!selectedRelationship.value) return

  ElMessageBox.confirm('确定要删除这个关系吗？此操作不可逆。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 这里应调用删除关系的API
        ElMessage.success('关系已删除')
        // 更新本地数据
        relationships.value = relationships.value.filter(
          (r) => r.id !== selectedRelationship.value.id,
        )
        selectedRelationship.value = null
        // 更新图表
        nextTick(() => {
          initGraph()
        })
      } catch (error) {
        console.error('删除关系失败:', error)
        ElMessage.error('删除关系失败: ' + (error.message || '未知错误'))
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 显示添加关系对话框
const showAddRelationDialog = () => {
  isEditingRelation.value = false
  Object.assign(relationForm, {
    id: null,
    source_field_id: '',
    target_field_id: '',
    relationship_type: 'reference',
    description: '',
  })
  relationFormVisible.value = true
}

// 编辑关系
const editRelationship = (relation) => {
  isEditingRelation.value = true
  Object.assign(relationForm, {
    id: relation.id,
    source_field_id: relation.source_field_id,
    target_field_id: relation.target_field_id,
    relationship_type: relation.relationship_type,
    description: relation.description || '',
  })
  relationFormVisible.value = true
}

// 确认删除关系
const confirmDeleteRelationship = (relation) => {
  ElMessageBox.confirm('确定要删除这个关系吗？此操作不可逆。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 这里应调用删除关系的API
        ElMessage.success('关系已删除')
        // 更新本地数据
        relationships.value = relationships.value.filter((r) => r.id !== relation.id)
        // 更新图表
        if (viewMode.value === 'graph') {
          nextTick(() => {
            initGraph()
          })
        }
      } catch (error) {
        console.error('删除关系失败:', error)
        ElMessage.error('删除关系失败: ' + (error.message || '未知错误'))
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 提交关系表单
const submitRelationForm = async () => {
  if (!relationFormRef.value) return

  await relationFormRef.value.validate(async (valid) => {
    if (!valid) return

    submitting.value = true
    try {
      // 构建提交数据
      const data = {
        source_field_id: relationForm.source_field_id,
        target_field_id: relationForm.target_field_id,
        relationship_type: relationForm.relationship_type,
        description: relationForm.description,
      }

      if (isEditingRelation.value && relationForm.id) {
        // 更新现有关系
        // 这里应调用更新关系的API

        // 更新本地数据
        const index = relationships.value.findIndex((r) => r.id === relationForm.id)
        if (index !== -1) {
          relationships.value[index] = {
            ...relationships.value[index],
            ...data,
          }
        }

        ElMessage.success('关系已更新')
      } else {
        // 创建新关系
        // 这里应调用创建关系的API

        // 模拟创建后的数据
        const newRelation = {
          id: Date.now().toString(),
          ...data,
        }
        relationships.value.push(newRelation)

        ElMessage.success('关系已创建')
      }

      relationFormVisible.value = false

      // 更新图表
      if (viewMode.value === 'graph') {
        nextTick(() => {
          initGraph()
        })
      }
    } catch (error) {
      console.error(isEditingRelation.value ? '更新关系失败:' : '创建关系失败:', error)
      ElMessage.error(
        (isEditingRelation.value ? '更新' : '创建') + '关系失败: ' + (error.message || '未知错误'),
      )
    } finally {
      submitting.value = false
    }
  })
}

// 监听视图模式变化
watch(viewMode, (newVal) => {
  if (newVal === 'graph') {
    nextTick(() => {
      initGraph()
    })
  }
})

// 监听datasetId变化
watch(
  () => props.datasetId,
  (newVal) => {
    if (newVal && dialogVisible.value) {
      loadData()
    }
  },
)

// 监听对话框可见性变化
watch(dialogVisible, (newVal) => {
  if (newVal && props.datasetId) {
    loadData()
  }
})

// 加载数据
const loadData = async () => {
  await fetchFields()
  await fetchRelationships()
  if (viewMode.value === 'graph') {
    nextTick(() => {
      initGraph()
    })
  }
}

// 组件挂载时加载数据
onMounted(() => {
  if (props.datasetId && dialogVisible.value) {
    loadData()
  }
})
</script>

<style scoped>
.relation-dialog :deep(.el-dialog__body) {
  padding: 0;
  height: calc(80vh - 120px);
}

.relation-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 15px;
}

.toolbar {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 图形视图样式 */
.graph-view {
  flex: 1;
  display: flex;
  position: relative;
  height: 100%;
}

.graph-container {
  flex: 1;
  height: 100%;
  min-height: 400px;
}

.relation-detail-card {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 300px;
  z-index: 10;
  opacity: 0.9;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 表格视图样式 */
.table-view {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-actions {
  margin-bottom: 10px;
}

.table-view :deep(.el-table) {
  flex: 1;
}
</style>
